package com.example.douyinproject.firstpage_news;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.douyinproject.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 新闻碎片
 * ListView
 * 1、布局填写，代码查找 2、数据源 3、适配器
 */
public class NewsFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1; //标题
    private String mParam2; //网址
    ListView lv; //列表视图
    List<NewsBean.DataBean.FeedlistBean> feedlist;
    private NewsBaseAdapter adapter;
    boolean isHaveHeader = false;

    public NewsFragment() {
        // Required empty public constructor
    }

    public static com.example.douyinproject.firstpage_news.NewsFragment newInstance(String param1, String param2) {
        com.example.douyinproject.firstpage_news.NewsFragment fragment = new com.example.douyinproject.firstpage_news.NewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        lv = view.findViewById(R.id.frag_lv);
        feedlist = new ArrayList<>();
        //设置适配器
        adapter = new NewsBaseAdapter(getContext(), feedlist);
        lv.setAdapter(adapter);
        connectNetwork(mParam1);
        setItemClick();
        return view;
    }

    //设置listview每一条点击事件的方法
    private void setItemClick() {
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsBean.DataBean.FeedlistBean.ItemsBeanX beanX = null;
                if (isHaveHeader) { //有头布局
                    beanX = feedlist.get(position-1).getItems().get(0);
                } else { //没有头布局
                    beanX = feedlist.get(position).getItems().get(0);
                }
                String fileurl = beanX.getFileurl(); //二级页面的网址
                Intent intent = new Intent(getContext(), InfoActivity.class);
                intent.putExtra("url",fileurl);
                startActivity(intent);
            }
        });
    }

    private void setVpItemClick(View view, NewsBean.DataBean.BannerBean.ItemsBean itemsBean) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fileurl = itemsBean.getFileurl(); //传值网址
                Intent it = new Intent(getActivity(),InfoActivity.class);
                it.putExtra("url",fileurl);
                startActivity(it);
            }
        });
    }

    /*在Android中链接网络，不能在主线程当中完成，会报错。
    安卓原生提供了两种方法：
    1、使用子线程Thread连接网络，然后将数据传递给主线程，在主线程当中更新UI；
    2、使用AsyncTask异步任务类，在方法doInBackground当中连接网络，在onPostExecute当中更新UI。
       也可以使用框架完成联网操作:如 okhttp retrofit volley xutils */
    private void connectNetwork(String url) {
        //1、构造请求参数
        RequestParams params = new RequestParams(url);
        //2、发起请求
        //发起请求之前要先声明
        x.http().get(params, new Callback.CacheCallback<String>() {
            @Override
            public boolean onCache(String result) {
                return false;
            }

            //请求成功时会调用的方法
            @Override
            public void onSuccess(String result) {
                //1、解析数据 Gson
                NewsBean newsBean = new Gson().fromJson(result, NewsBean.class);
                NewsBean.DataBean data = newsBean.getData();
                List<NewsBean.DataBean.FeedlistBean> list = data.getFeedlist(); //显示的数据源
                //2、将获取到的数据添加到listview的数据源中
                feedlist.addAll(list);
                //3、通知适配器更新数据
                adapter.notifyDataSetChanged();

                //得到轮播条对象
                NewsBean.DataBean.BannerBean banner = data.getBanner();
                if (banner.getCount()>0) {
                    //给listview添加banner头布局
                    isHaveHeader = true; //有头布局
                    View headerView = getHeaderView(banner);
                    lv.addHeaderView(headerView);
                }
            }

            //请求失败时会调用的方法
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("shanzhikai","onError: ex=="+ex.getMessage());
            }

            //请求被取消时会调用的方法
            @Override
            public void onCancelled(CancelledException cex) {

            }

            //请求完成时会调用的方法
            @Override
            public void onFinished() {

            }
        });
    }

    /*获取头布局的方法*/
    private View getHeaderView(NewsBean.DataBean.BannerBean banner) {
        View headerView = getLayoutInflater().inflate(R.layout.item_headerview,null);
        ViewPager headerVp = headerView.findViewById(R.id.header_vp);
        LinearLayout headerLayout = headerView.findViewById(R.id.header_layout);
        //给viewpager填充数据
        List<NewsBean.DataBean.BannerBean.ItemsBean> itemsList = banner.getItems();
        List<View>viewList = new ArrayList<>();
        List<ImageView>pointList = new ArrayList<>(); //管理小点的集合
        for (int i = 0; i < itemsList.size(); i++) {
            NewsBean.DataBean.BannerBean.ItemsBean itemsBean = itemsList.get(i); //得到指定位置的数据
            View view = getLayoutInflater().inflate(R.layout.item_vp, null);
            TextView tv = view.findViewById(R.id.item_vp_tv);
            ImageView iv = view.findViewById(R.id.item_vp_iv);
            tv.setText(itemsBean.getTitle());
            Picasso.with(getContext()).load(itemsBean.getImg()).into(iv);
            //给viewpager当中每一个view添加单击事件
            setVpItemClick(view,itemsBean);

            viewList.add(view); //添加viewpager的数据源当中，统一管理

            //初始化每一个小点
            ImageView pointView = new ImageView(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0,0,8,0); //设置外边距
            pointView.setLayoutParams(params); //设置布局参数
            pointView.setImageResource(R.mipmap.p1);
            headerLayout.addView(pointView); //将小点放到布局当中
            pointList.add(pointView); //将小点放到集合当中，便于统一管理
        }
        pointList.get(0).setImageResource(R.mipmap.p2); //默认第一个是选中状态
        setHeaderVpListener(pointList,headerVp);

        //设置适配器
        HeaderPagerAdapter headerPagerAdapter = new HeaderPagerAdapter(getContext(), viewList);
        headerVp.setAdapter(headerPagerAdapter);
        return headerView;
    }

    /*监听headerview当中的viewpager活动到哪个页面了*/
    private void setHeaderVpListener(List<ImageView> pointList, ViewPager headerVp) {
        headerVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < pointList.size(); i++) {
                    pointList.get(i).setImageResource(R.mipmap.p1);
                } //被选中的位置是粉色的
                pointList.get(position).setImageResource(R.mipmap.p2);
            }
        });
    }
}